/**
 */
"use strict";

var Router = require('koa-router');
var config = require('../../config/config.js');
var router = new Router({
    prefix: config.baseUrl
});
module.exports = router.routes();
console.log('router:' + config.baseUrl + ', logstash');

router.get('/**', logstash);
router.post('/**', logstash);
router.put('/**', logstash);
router.delete('/**', logstash);

function* logstash(next) {
    var json = {
        method: this.request.method,
        url: this.request.url,
        uid: __randomInt(1, 3),
        realm: __randomInt(1, 4), // article, shop, ware
        action: __randomInt(1, 5), // read, post, delete, edit, favor
        tags: __randomTagsArray(),
        detail: ''
    };


    yield next;

    json.resCode = this.status;
    __logstash(json);
}

/**
 * 1. send log(json) to redis
 * 2. (optional) curd mysql
 */
function __logstash(json) {
    process.nextTick(function () {
        __saveToRedis(json);
    });

    return 'ok';
}

var redis = require('../../model/redis.js').client;
var __list = 'logstash:api';

function __saveToRedis(json) {
    redis.lpush([__list, JSON.stringify(json)], function (err, res) {
        if (err) {
            return console.log('log -> redis err:', err);
        }
        console.log(res);
        __updateMysql(json);
    });
}

var rtToi = require('../../dao/rtToi.js');

function __updateMysql(json) {
    rtToi.addOne2(json).then(function (doc) {
        console.log('__updateMysql succ:');
    });
}


function __randomInt(low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

var __topic = ["宝宝", "结婚", "感情", "父母", "职场", "怀孕"];
var __minLen = 1;
var __maxLen = __topic.length;

function __randomTagsArray() {
    var tmp = [];
    tmp = tmp.concat(__topic);
    var len = __randomInt(__minLen, __maxLen + 1);
    var result = [];
    for (var i = 0; i < len; i++) {
        var rdm = __randomInt(0, tmp.length);
        var item = tmp.splice(rdm, 1)[0];
        result.push(item);
    }
    return result;
}